package com.example.tree;


/**
 * Trie（发音类似 "try"）或者说 前缀树 是一种树形数据结构，用于高效地存储和检索字符串数据集中的键。
 * 这一数据结构有相当多的应用情景，例如自动补完和拼写检查。
 * <p>
 * 请你实现 Trie 类：(leetcode208)
 * Trie() 初始化前缀树对象。
 * void insert(String word) 向前缀树中插入字符串 word 。
 * boolean search(String word) 如果字符串 word 在前缀树中，返回 true（即，在检索之前已经插入）；否则，返回 false
 * 。
 * boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ，返回 true ；否则，返回 false 。
 * 示例：
 * 输入
 * ["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
 * [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
 * 输出
 * [null, null, true, false, true, null, true]
 * <p>
 * word 和 prefix 仅由小写英文字母组成
 */
public class Trie {
    private TrieNode root;

    public static void main(String[] args) {
        Trie trie = new Trie();

        trie.insert("apple");
        System.out.println(trie.search("apple"));
        System.out.println(trie.search("app"));
        System.out.println(trie.startsWith("app"));
        trie.insert("app");
        System.out.println(trie.search("app"));

    }

    public Trie() {
        root = new TrieNode();
    }

    /**
     * Inserts a word into the trie.
     */
    public void insert(String word) {
        TrieNode tmp = root;
        for (int i = 0; i < word.length(); i++) {
            int pos = word.charAt(i) - 'a';
            if (tmp.children[pos] == null) {
                tmp.children[pos] = new TrieNode();
            }
            tmp = tmp.children[pos];
        }
        tmp.isWord = true;
    }

    /**
     * Returns if the word is in the trie.
     */
    public boolean search(String word) {
        TrieNode tmp = root;
        for (int i = 0; i < word.length(); i++) {
            int pos = word.charAt(i) - 'a';
            if (tmp.children[pos] == null) {
                return false;
            }
            tmp = tmp.children[pos];
        }
        return tmp.isWord;
//        return searchByRecursion(word, 0, root);
    }

    private boolean searchByRecursion(String word, int n,TrieNode tmp) {
        if (n <= word.length() - 1) {
            int index = word.charAt(n) - 'a';
            if (tmp.children[index] == null) {
                return false;
            }
            return searchByRecursion(word, ++n, tmp.children[index]);
        }
        return tmp.isWord;

    }

    /**
     * 查询当前trie中是否存在仅有一个字符和所给的搜索字符不匹配(实现魔法字符串的查询)
     *
     * @param word
     * @return
     */
    public boolean searchForOnlyHasOneNotMatch(String word) {
        TrieNode presentNode = root;
        for (int i = 0; i < word.length(); i++) {// 遍历待搜索字符
            char c = word.charAt(i);
            for (int j = 0; j < 26; j++) {// 遍历当前结点的所有子结点
                if ((char)(j + 'a') == c || presentNode.children[j] == null)
                    continue;
                if (partSearch(presentNode.children[j], word, i + 1))//如果剩余字符存在当前子结点为root的Trie中，返回true
                    return true;
            }
            if (presentNode.children[c - 'a'] == null)
                return false;

            presentNode = presentNode.children[c - 'a'];
        }
        return false;
    }

    public boolean partSearch(TrieNode temp, String word, int index) {
        for (int i = index; i < word.length(); i++) {
            char c = word.charAt(i);
            if (temp.children[c - 'a'] == null)
                return false;
            temp = temp.children[c - 'a'];
        }
        return temp.isWord;
    }



    /**
     * Returns if there is any word in the trie that starts with the given prefix.
     */
    public boolean startsWith(String prefix) {
        TrieNode tmp = root;
        for (int i = 0; i < prefix.length(); i++) {
            int pos = prefix.charAt(i) - 'a';
            if (tmp.children[pos] == null) {
                return false;
            }
            tmp = tmp.children[pos];
        }
        return true;
    }

    private class TrieNode {
        public TrieNode[] children;
        public boolean isWord;

        public TrieNode() {
            children = new TrieNode[26];
            isWord = false;
        }

    }
}
